#!/usr/bin/env python3
import psutil
import time
import pymysql

# 数据库
try:
    db = pymysql.connect(host='localhost',user='root',passwd='123456',db='python')
except Exception as e:
    print(e)
    exit()
db.autocommit(True)
cur = db.cursor()
SQL_TEMPLATE = 'insert into net(time,sent,recv) values({0},{1},{2})'

# 初始发送和接收
sent,recv,*rest = psutil.net_io_counters()

def main():
    try:
        while True:
            global sent,recv
            time.sleep(1)

            t = int(time.time())
            sent_new,recv_new,*rest = psutil.net_io_counters()
            sent_delta, recv_delta = sent_new - sent, recv_new - recv
            sent, recv = sent_new, recv_new

            cur.execute(SQL_TEMPLATE.format(t, sent_delta, recv_delta))
            print('time:{0} sent:{1} bytes recv:{2} bytes'.format(t,sent_delta,recv_delta))
    except BaseException as e:
        print(e)
    finally:
        if 'db' in globals():
            db.close()

main()
